package com.example.demo.controller;

import com.example.demo.aspect_.DataSourceAnnotation;
import com.example.demo.config.DataSourceContextHolder;
import com.example.demo.constant.RedisConstant;
import com.example.demo.entity.User;
import com.example.demo.service.ChangeDataSourceService;
import com.example.demo.service.UserService;
import com.example.demo.util.R;
import com.example.demo.util.Redis2Service;
import com.example.demo.util.ResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * @author makejava
 * @since 2022-04-01 17:11:09
 */
@Api(tags = "(User)")
@Validated
@RestController
@AllArgsConstructor
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private Redis2Service redis2Service;

//    @DataSourceAnnotation   //注解方式实现切面
    @GetMapping("list")
    @RequiresPermissions("user:list")
    public ResponseEntity<R<List<User>>> list(){
        List<User> list1 = userService.list();
        System.out.println(list1);
        return ResultUtil.success(list1);
    }

//    @DataSourceAnnotation   //注解方式实现切面
    @PostMapping("register")
    @RequiresPermissions("user:create")
    public ResponseEntity<R<String>> save(@RequestBody User user){
        ByteSource salt = ByteSource.Util.bytes(user.getAccount());
        String password = user.getPassword();
        password = new SimpleHash("sha-1", //加密方式
                password,//密码原值
                salt,//盐值
                916//加密次数
        ).toString();
        user.setPassword(password);
        userService.save(user);
        return ResultUtil.successMsg("注册成功");
    }

    /**
     * 删除用户
     * @param id    用户id
     * @return
     */
    @GetMapping("delete")
    @RequiresPermissions("user:delete")
    public ResponseEntity<R<String>> delete(Integer id){

        boolean b = userService.removeById(id);
        return ResultUtil.successMsg("删除成功");
    }

}

